package pages;

import java.util.Collection;

import webserver.HttpRequest;
import dao.DAO;
import dao.models.Answer;
import dao.models.Chapter;
import dao.models.Session;

public class ResultPage {

    private DAO dao = DAO.getInstance();

    public String getResultPage(HttpRequest rq) {
	String ssid = rq.getSSID();
	if (ssid == null) {
	    return "No test session set";
	}
	Session session = dao.getSessionById(ssid);
	if (session == null)
	    return "No test session exist";
	String prevAnswerId = rq.getValueByName("answer");
	if (prevAnswerId != null) {
	    String qid = rq.getValueByName("qid");
	    Answer prevAnswer = dao.getAnswerById(prevAnswerId);
	    session.answer(prevAnswer, qid);
	}
	StringBuilder sb = new StringBuilder();
	sb.append("Тест пройден.<br> Всего вопросов: "
		+ session.getTotalQuestionsCount()
		+ ".<br> Правильных ответов: " + session.getRightAnswersCount()
		+ ".<br> Процент выполнения: " + session.getPercent() + "%<br>");
	return sb.toString();
    }

    public String getChaptersToLookPage(HttpRequest rq) {
	String ssid = rq.getSSID();
	if (ssid == null) {
	    return "No test session";
	}
	Session session = dao.getSessionById(ssid);
	if (session == null)
	    return "No test session exist";
	String prevAnswerId = rq.getValueByName("answer");
	if (prevAnswerId != null) {
	    String qid = rq.getValueByName("qid");
	    Answer prevAnswer = dao.getAnswerById(prevAnswerId);
	    session.answer(prevAnswer, qid);
	}
	StringBuilder sb = new StringBuilder();
	Collection<Chapter> failedChapters = session.getFailedChapters();
	if (!failedChapters.isEmpty()) {
	    sb.append("<h3>Рекомендуем посмотреть следущие главы: </h3>");
	    for (Chapter chapter : failedChapters) {
		sb.append("\n<a href = \"./chapter.j?id=" + chapter.getId()
			+ "\"> Глава " + chapter.getId() + " - "
			+ chapter.getName() + "<br>");
	    }
	}
	return sb.toString();
    }
}
